const express = require("express");
const { createProxyMiddleware } = require("http-proxy-middleware");
const history = require("connect-history-api-fallback");
const configs = require("../configs/get-configs");
const app = express();
const port = configs["development"].static.staticPort;

// rap项目map
// const mockMap = {
//   companyService: 20,
//   toolService: 21,
//   examService: 22,
//   reportService: 26,
//   hrService: 23,
// };
function getEntryHtml(entry) {
  console.log(entry);
  switch (entry) {
    case "customer":
      return "/entry/mobile_index/index.html";
    case "admin":
      return "/entry/admin_index/index.html";
    // case "exam":
    //   return "/exam_index.html";
    // case "m/exam":
    //   return "/exam_m_index.html";
    // default:
    //   return "/admin_index.html";
  }
}

// /**
//  * 是否开启连接 rap
//  * @param configs
//  * @return Boolean
//  */
// function isRap(configs) {
//   return configs["development"].api.mock;
// }

app.use(
  history({
    index: "/page_entry",
    rewrites: [
      { from: /^\/(\/|$)/, to: "/page_entry" },
      // { from: /^\/exam(\/|$)/, to: "/page_entry" },
      // { from: /^\/m\/exam(\/|$)/, to: "/page_entry" },
    ],
  })
);

// app.use(
//   "/__open-in-editor",
//   createProxyMiddleware({
//     target: "http://localhost:8002",
//     changeOrigin: true,
//   })
// );

app.use(
  "/page_entry",
  createProxyMiddleware({
    target: "http://localhost:8002",
    changeOrigin: true,
    pathRewrite(path) {
      const entry = path.match(/^\/(?:((?:m\/)?\w+)(?:$|\/))?/)[1];
      return getEntryHtml(entry);
    },
  })
);

// if (isRap(configs)) {
//   // 开启mock后，会自动代理到对应的rap项目
//   Object.keys(mockMap).forEach((serviceName) => {
//     app.use(
//       `/api/${serviceName}`,
//       createProxyMiddleware({
//         target: `http://rap.cepin.net/mockjs/${mockMap[serviceName]}`,
//         changeOrigin: true,
//         pathRewrite: {
//           "^/api": "",
//         },
//       })
//     );
//   });
// }

// app.use(
//   "/api",
//   createProxyMiddleware({
//     target: configs["development"].api.host,
//     changeOrigin: true,
//     pathRewrite: {
//       "^/api": "",
//     },
//   })
// );

// app.use(
//   createProxyMiddleware("/tasatt", {
//     target: "http://tas5.cepin.net",
//     changeOrigin: true,
//     pathRewrite: (path) => path,
//   })
// );

app.use(
  createProxyMiddleware("/", {
    target: "http://localhost:8002",
    changeOrigin: true,
  })
);

app.listen(port, () =>
  console.log(`Tas5 Dev Server listening on port ${port}!`)
);
